<?php

/**
 * @Author: king
 * @Date:   2019-02-17 19:50:25
 * @Last Modified by:   king
 * @Last Modified time: 2019-05-18 18:04:35
 */

namespace App\Http\Controllers\Api\v1;

use App\Exceptions\ApiException;
use App\Http\Controllers\Api\BaseController;
use App\Http\Controllers\Api\v1\Everyday\IndexController;
use App\Models\Api\AwardUser;
use App\Models\Api\Fortune;
use App\Models\Api\FortuneCache;
use App\Models\Api\Fortunenote;
use App\Models\Api\Fortunesetting;
use App\Models\Api\Orders;
use App\Models\Api\Recode;
use App\Models\Api\User;
use Cache;
use DB;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;

/**
 * @title 每日运势相关接口
 * @desc
 * @url
 * @version 1.3.0
 * Class Fortune
 * @package app\api\controller\v2
 */
class FortuneController extends BaseController
{
    protected $nodel;

    public function __construct()
    {
       // parent::__construct();

        $this->nodel            = config('code.nodel');
        $this->award_user_model = new AwardUser();
        $this->orders_model     = new Orders();
        $this->recodeMdoel      = new Recode();
        $this->fortuneNoteModel = new Fortunenote();
    }

    /**
     * @title 每日运势详情
     * @method GET
     * @desc
     * @return Json
     * @throws \ApiException
     */

    public function index(Request $request)
    {
        if (!$request->isMethod('get')) {
            return show(config('code.error'), '未知操作', [], 403);
        }
        $rid = $request->input('rid');
        //if($this->headers['app-type'] === 'ios'){
         $time =strtotime($request->input('time'));
       // }else{
        // $time =strtotime( $request->input('time'));
       // }
        // 当前时间
        //$time = strtotime(date('Y-m-d', $request->input('time')));
        $uid  = $request->uid;

        if (!$rid) {
            throw new ApiException('档案信息获取失败', 200, config('code.error'));
        }

        $arr = (new Fortune())->getUserUnlockFortune(['uid' => $uid, 'time' => $time, 'rid' => $rid]);
        //\Log::info(var_export($arr));
        $is_unlock   = $arr['is_unlock'];
        $seven       = $arr['seven'];
        $fortune     = $arr['fortune'];
        $selfId      = $arr['selfId'];
        $note_status = $arr['note_status'];
        
        if ($is_unlock === true) {

            $is_use_cache = 1;
            if ($is_use_cache) {
                $map             = ['time' => $time, 'rid' => $rid];
                $data            = (new FortuneCache())->getDetailFortune($map);
                $data['time']    = $seven;
                $data['fortune'] = $fortune;
            } else {
                $dailyFortune = new IndexController();

                $data              = $dailyFortune->init($rid, strtotime(date('Y-m-d', $time) . ' 12:00:00'));
                $data['time']      = $seven;
                $data['fortune'][] = $fortune;
                $temp[]            = $data['fortune_list'][4];
                $temp[]            = $data['fortune_list'][3];
                $temp[]            = $data['fortune_list'][1];
                $temp[]            = $data['fortune_list'][0];
                $temp[]            = $data['fortune_list'][6];
                $temp[]            = $data['fortune_list'][2];
                $temp[]            = $data['fortune_list'][5];
                $temp[]            = $data['fortune_list'][7];
                $temp[]            = $data['fortune_list'][8];
                //婚恋/学习/事业/财富/出行/健康/交际/家人/心情
                $data['fortune_list'] = $temp;
            }

        }

        // 去重
        $seven = array_unique($seven);
        // 重新索引
        $data['time'] = array_values($seven);

        // 去重
        $fortune = array_unique($fortune);
        // 重新索引
        $data['fortune']     = array_values($fortune);
        $data['self_rid']    = $selfId['id'];
        $data['note_status'] = $note_status;
        //用来判断是否可以写日记
        Cache::set($request->uid . date('Y-m-d', $time), $is_unlock, 86400);

        return show(200, '加载成功', $data);
    }

    /**
     * @title 根据年月获取日记标识
     * @method GET
     * @desc
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function note_time(Request $request)
    {
        if (!$request->isMethod('get')) {
            return show(config('code.error'), '未知操作', [], 403);
        }

    //   if($this->headers['app-type'] === 'ios'){
    //      $time = strtotime(date('Y-m', strtotime($request->input('time'))));
    //     }else{
    //     $time = strtotime(date('Y-m', $request->input('time')) . '-01');
    //     }
        // 当前查看的具体日期
         $time = strtotime(date('Y-m', strtotime($request->input('time'))) . '-01');

        $rid = $request->input('rid');

        // 返回值初始化
        $arr = [
            'time'    => [],
            'fortune' => [],
        ];

        // 获取日记标识
        $times = $this->fortuneNoteModel->getRidNote(['rid' => $rid]);

        // 是否有日记的日期
        foreach ($times as $k => $v) {
            $date = strtotime(date('Y-m', $v['time']));

            if ($time == $date) {
                $arr['time'][] = date('d', $v['time']);
            }
        }

        // 查询当前用户是否为VIP 或 vip2
        $unlock_users = getVip($request->uid);

        // 获取当前用户的档案id
        $selfId = $this->recodeMdoel->getSelfRecode(['uid' => $request->uid]);

        if ($unlock_users === 1 || ($unlock_users > 1 && $rid == $selfId['id'])) {

            for ($i = $time; $i < strtotime('+1 month', $time); $i += 86400) {
                $arr['fortune'][] = date('d', $i);
            }
        } // 非VIP 查询购买的订单 和  是否有赠送的 当月所有日期
        else {
            // 2018年年底活动  最后七天免费永久解锁
            if (date('Y-m', $time) == '2018-12') {
                $arr['fortune'][] = "25";
                $arr['fortune'][] = "26";
                $arr['fortune'][] = "27";
                $arr['fortune'][] = "28";
                $arr['fortune'][] = "29";
                $arr['fortune'][] = "30";
                $arr['fortune'][] = "31";
            }

//        获取档案购买的订单
            $fortuneOrders = $this->orders_model->fortune_orders(['uid' => $request->uid, 'rid' => $rid, 'type' => 1]);

            $arr1 = [];

            $arr2 = [];

            //获取当前月份 总共有多少天
            $month = month_days($time);

            if (!empty($fortuneOrders)) {
                foreach ($fortuneOrders as $k => $v) {
                    if (in_array($rid, explode(',', $v['rids']))) {
                        $extime = json_decode($v['extend'], true)['expire_time'];

                        if (isset($extime) || !empty($extime)) {
                            $v['expire_time'] = $extime;
                        }
                        $date = strtotime(date('Y-m', $v['time']));

                        $end_time = strtotime('-1 days', strtotime($v['expire_time'], $v['time']));

                        if (in_array($v['gid'], [3, 4, 5, 6])) {
                            if (($time >= $date) && $time <= $end_time) {
                                $order_start_time = strtotime(date('Y-m-d', $v['time']));
                                $order_end_time   = strtotime(date('Y-m-d', $end_time));
                                // 遍历当前月份的具体日期
                                foreach ($month as $kk => $vv) {
                                    if ($order_start_time <= $vv && $vv <= $order_end_time) {
                                        $arr1[] = date('d', $vv);
                                    }
                                }
                            };
                        } elseif ($v['gid'] == 2) {
                            if (($time >= $date) && $time <= $end_time) {
                                $arr1[] = date('d', $v['time']);
                                $extime = json_decode($v['extend'], true)['expire_time'];
                                if (isset($extime) || !empty($extime)) {
                                    $arr1[] = date('d', strtotime('+1day', $v['time']));
                                }
                            }
                        }
                    }

                }
            }
//        获取中奖纪录
            $prize = $this->award_user_model->get_award_fortune(['uid' => $request->uid, 'rid' => $rid, 'type' => 1]);

            if (!empty($prize)) {
                //  遍历所有获赠的日运
                foreach ($prize as $k => $v) {
                    $extend = json_decode($v['extend'], true);
                    // 获赠的日运的开始时间 时间戳
                    $date = strtotime(date('Y-m', $extend['award_time']));
                    // 获赠的日运的结束时间
                    $end_time = strtotime('-1 days', strtotime($v['expire_time'], $extend['award_time']));

                    // 获取赠送的日运记录
                    if (in_array($v['aid'], [3, 4, 5, 6])) {
                        //判断当前查看的月份是否在赠送的范围内
                        if (($time >= $date) && $time <= $end_time) {
                            $extend_start_time = strtotime(date('Y-m-d', $extend['award_time']));
                            $extend_end_time   = strtotime(date('Y-m-d', $end_time));
                            // 遍历当前月份的具体日期
                            foreach ($month as $kk => $vv) {
                                // 判断获赠的具体日期是否在当前月具体日期内
                                if ($extend_start_time <= $vv && $vv <= $extend_end_time) {
                                    $arr2[] = date('d', $vv);
                                }
                            }
                        }

                    } // 获取赠送一日的日运记录
                    elseif ($v['aid'] == 2) {
                        // 当前查看的具体日期是否和赠送的具体日期一样
                        if ($time == $date) {
                            $arr2[] = date('d', $extend['award_time']);
                        }
                    }
                }
            }
            // 合并活动的日期，订单购买的日期，后台赠送的日期
            if (date('Y-m', $time) == date('Y-m', time())) {
                $arr['fortune'][] = date('d', time());
            }
            $arr['fortune'] = array_merge($arr['fortune'], $arr1, $arr2);
            // 去重
            $arr['fortune'] = array_unique($arr['fortune']);
            // 重新索引
            $arr['fortune'] = array_merge($arr['fortune']);
        }
        return show(200, '成功', $arr);
    }

    /**
     * @title 获取运势图标设置
     * @method GET
     * @desc
     * @return array
     */
    public function chart_list(Request $request)
    {
        if (!$request->isMethod('get')) {
            return show(config('code.error'), '未知操作', [], 403);
        }
        $data1 = Cache::get('fortune_setting_' . $request->uid);
        try
        {
            if ($data1) {
                $arr = $data1;
            } else {
                $arr = Fortunesetting::where(['uid' => '0'])
                    ->first(['name'])->toArray();
                Cache::set('fortune_setting_' . $request->uid, $arr, 86400 * 3);
            }

            $name = explode(',', $arr['name']);

            foreach ($name as $k => $v) {
                foreach (config('fortune')['set'] as $kk => $vv) {
                    if ($k == $kk) {
                        $data[] = [
                            'id'     => $k,
                            'name'   => $vv,
                            'status' => $v,
                        ];
                    }
                }
            }
        } catch (\Exception $e) {
            return show(config('code.error'), $e->getMessage(), [], 500);
        }
        return show(200, '提交成功', $data);
    }

    /**
     * @title 更新运势图标设置
     * @method PUT
     * @desc
     * @return array
     */
    public function chart_save(Request $request)
    {

        if (!$request->isMethod('put')) {
            return show(config('code.error'), '未知操作', [], 403);
        }
        $ids = explode(',', $request->input('ids'));

        if (count($ids) !== 5) {
            return show(config('code.error'), '必须显示5项');
        }
        $name = config('fortune.set');
        try
        {
            $arr1 = Fortunesetting::where(['uid' => $request->uid])
                ->update(['name' => implode(',', $name)]);

            foreach ($name as $k => $v) {
                if (in_array($k, $ids)) {
                    $name[$k] = 1;
                } else {
                    $name[$k] = 0;
                }

            }
            if ($arr1) {
                DB::table('app_fortune_setting')
                    ->where('uid', $request->uid)
                    ->update(['name' => implode(',', $name)]);
            } else {
                Fortunesetting::insert([
                    'name' => implode(',', $name),
                    'uid'  => $request->uid,
                ]);
            }

            $arr = Fortunesetting::where(['uid' => $request->uid])->first(['name']);

            Cache::set('fortune_setting_' . $request->uid, $arr, 86400 * 3);

        } catch (\Exception $e) {
            return show(config('code.error'), $e->getMessage(), [], 500);
        }
        return show(200, '更新成功', []);

    }

    /**
     * @title 运势日记列表
     * @method GET
     * @desc
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function note(Request $request)
    {
        if (!$request->isMethod('get')) {
            return show(config('code.error'), '未知操作', [], 403);
        }
        $page        = $request->input('page', 1);
        $uid         = $request->uid;
        $map         = ['uid' => $uid, 'isself' => 1];
        $recode_info = (new Recode())->getSelfRecode($map);

        $is_use_cache = 1;
        if ($is_use_cache) {
            $map['rid']  = $recode_info['id'];
            $map['page'] = $page;

            try {
                $data = $this->fortuneNoteModel->getListPage($map);
            } catch (\Exception $e) {

                return show(config('code.error'), '网络错误');
            }

            if (isset($data['data']) && !empty($data['data'])) {
                foreach ($data['data'] as $k => $v) {

                    $data['data'][$k] = [
                        'id'          => $v['id'],
                        'create_time' => $v['create_time'],
                        'content'     => $v['content'],
                        'state'       => $v['state'],
                        'mood'        => $v['mood'],
                        'from'        => [
                            'rid'      => $v['rid'],
                            'time'     => $v['time'],
                            'remark'   => '每日运势',
                            'icon_url' => config('fortune.thumb'),
                        ],
                    ];
                }
                return show(200, '列表加载成功', $data);
            } else {
                return show(200, '还没有运势日记，您可以为每日运势打分哦~', $data);
            }

        } else {
            $where = [['status', '!=', config('code.status_delete')], 'rid' => $recode_info['id']];
            try {
                $data = Fortunenote::select('id', 'rid', 'time', 'state', 'mood', 'content', 'from', 'create_time')
                   //->where('status', '!=', config('code.status_delete'))
                   ->orWhere('rid', $recode_info['id'])
                    ->orderBy('id', 'DESC')
                    ->paginate(10, false, $page)->toArray();

            } catch (\Exception $e) {

                return show(config('code.error'), '网络错误');
            }

            if (isset($data['data']) && !empty($data['data'])) {
                foreach ($data['data'] as $k => $v) {
                    if ($v['from'] == 1) {
                        $from = '每日运势';
                    }
                    $data['data'][$k] = [
                        'id'          => $v['id'],
                        'create_time' => $v['create_time'],
                        'content'     => $v['content'],
                        'state'       => $v['state'],
                        'mood'        => $v['mood'],
                        'from'        => [
                            'rid'      => $v['rid'],
                            'time'     => $v['time'],
                            'remark'   => $from,
                            'icon_url' => config('fortune.thumb'),
                        ],
                    ];
                }
                return show(200, '列表加载成功', $data);
            } else {
                return show(200, '还没有运势日记，您可以为每日运势打分哦~', $data);
            }
        }
    }

    /**
     * @title 新建日记
     * @method POST
     * @desc
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function save(Request $request)
    {
        if (!$request->isMethod('post')) {
            return show(config('code.error'), '未知操作', [], 403);
        }
        $content = htmlspecialchars($request->input('content'));

        // if($this->headers['app-type'] === 'ios'){
        //  $time =strtotime($request->input('time'));
        // }else{
         //$time =strtotime(date('Y-m-d', $request->input('time')));
         $time =strtotime($request->input('time'));
       // }
        $state   = $request->input('state');
        $mood    = $request->input('mood');
        $from    = $request->input('from');

//        获取档案id
        $rid = $this->recodeMdoel->getSelfRecode(['uid' => $request->uid]);

        $data = [
            'rid'         => $rid['id'],
            'content'     => $content,
            'from'        => $from,
            'state'       => $state,
            'mood'        => $mood,
            'time'        => $time,
            'create_time' => time(),
        ];

        if (trim($content) == '') {
            return show(config('code.error'), '内容不能为空');
        }
        $id = Fortunenote::insertGetId($data);
        Cache::forget('fortune_note_ids_' . $rid['id']);//删除运势日记ids
        Cache::forget('fortune_note_' . $rid['id']);

        if ($from == 1) {
            $from = '每日运势';
        }
        $array = [
            'id'          => $id,
            'create_time' => time(),
            'content'     => $content,
            'state'       => $state,
            'mood'        => $mood,
            'from'        => [
                'rid'      => $rid['id'],
                'time'     => $time,
                'remark'   => $from,
                'icon_url' => config('fortune.thumb'),
            ],
        ];

        return show(200, 'Success', $array);
    }

    /**
     * @title 编辑日记
     * @method PUT
     * @desc
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function update(Request $request)
    {
        if (!$request->isMethod('put')) {
            return show(config('code.error'), '未知操作', [], 403);
        }
        $id      = $request->input('id');
        $content = htmlspecialchars($request->input('content'));
        $state   = $request->input('state');
        $mood    = $request->input('mood');
        //        获取档案id
        $rid  = $this->recodeMdoel->getSelfRecode(['uid' => $request->uid]);
        $data = [
            'content' => $content,
            'state'   => $state,
            'mood'    => $mood,
        ];
        if (trim($content) == '') {
            return show(config('code.error'), '内容不能为空');
        }
        try
        {
            Fortunenote::where(['id' => $id, 'rid' => $rid['id']])->update($data);
        } catch (\Exception $e) {
            \Log::info('更新运势日记失败' . $e->getMessage() . 'update_fortune_note_error');

            return show(config('code.error'), '网络错误');
        }

        Cache::forget('fortune_note_' . $rid['id']);
        $arr = Fortunenote::where(['id' => $id])->first(['time', 'from'])->toArray();

        if ($arr['from'] == 1) {
            $from = '每日运势';
        }
        // 组合返回的数据
        $array = [
            'id'          => $id,
            'create_time' => time(),
            'content'     => $content,
            'state'       => $state,
            'mood'        => $mood,
            'from'        => [
                'rid'      => $rid['id'],
                'time'     => $arr['time'],
                'remark'   => $from,
                'icon_url' => config('fortune.thumb'),
            ],
        ];

        return show(200, '修改成功', $array);

    }

    /**
     * @title 删除日记
     * @method DELETE
     * @desc
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function del(Request $request)
    {
        if (!$request->isMethod('delete')) {
            return show(config('code.error'), '未知操作', [], 403);
        }
        $id   = $request->input('id');
        $rids = $this->recodeMdoel->getSelfRecode(['uid' => $request->uid]);

        try
        {
            Fortunenote::where(['id' => $id, 'rid' => $rids['id']])->delete();
            Cache::forget(FortuneNote::REDIS_KEY_FORTUNE_NOTE_IDS . $rids['id']);
            Cache::forget(FortuneNote::REDIS_KEY_FORTUNE_NOTE_DETAIL . $id);

        } catch (\Exception $e) {
            \Log::info('删除运势日记失败' . $e->getMessage());

            return show(config('code.error'), '网络错误');
        }
        Cache::forget('fortune_note_' . $rids['id']);
        return show(200, '删除成功');
    }

    /**
     * @title 选择开通方式
     * @method GET
     * @desc
     * @return array
     */
    public function unlock_type(Request $request)
    {
        if (!$request->isMethod('get')) {
            return show(config('code.error'), '未知操作', [], 403);
        }
        $goods = [];
        try
        {
            $goods = DB::table('goods')
                ->select('id as gid', 'now_prize as price', 'name')
                ->whereIn('id', $this->fortuneGoods)
                ->get();
        } catch (\Exception $e) {
            \Log::info('更新运势日记失败' . $e->getMessage());

        }
        return show(config('code.success'), 'success', $goods);
    }
}
